import sys

from docx import Document


def gen_docx(title, contents, think, num):
    tpl = Document('template.docx')
    tab = tpl.tables[0]
    cell_title = tab.rows[1].cells[2]  # 题目
    cell_art = tab.rows[2].cells[1]  # 文献内容
    cell_thk = tab.rows[3].cells[1]  # 文献启发

    cell_title.text = title
    cell_art.text = contents
    cell_thk.text = think

    tpl.save("文献阅读记录{}.docx".format(num))


# if __name__ == '__main__':
def docx_gen():
    with open('docx_pre.tmp',encoding='utf-8') as art:
        lines = art.readlines()
        lines = [line[0:-1] for line in lines if line[0] != '#' and line != "\n"]  # 去除空行和注释
        if len(lines) % 4 != 0:
            print('ERROR: docx_pre.tmp format not meet')
            sys.exit(1)
        for index in range(0,len(lines),4):
            gen_docx(lines[index+1],lines[index+2],lines[index+3],lines[index])


if __name__ == '__main__':
    docx_gen()
